<?php
require_once($_SERVER['DOCUMENT_ROOT'] .'/config.inc');
require_once(ROOT . LIBRARY .'/db.class.inc');

$DB = database::getInstance($_SYS['db']['host'], $_SYS['db']['name'], $_SYS['db']['user'], $_SYS['db']['pass']);
$DB->sql = "SET NAMES utf8";
$DB->DB_Query();

$backups = array();

if(in_array($_POST['action'], array('save', 'restore')) && in_array($_POST['type'], array('system', 'users', 'config')))
{
   switch($_POST['type'])
   {
      case 'system':
         $DB->sql = 'SELECT * FROM meccano_var WHERE sys <> "0"';
         $funcName = $_POST['action'].'Vars';
         break;

      case 'users':
         $DB->sql = 'SELECT * FROM meccano_var WHERE sys = 0';
         $funcName = $_POST['action'].'Vars';
         break;

      case 'config':
         $DB->sql = 'SELECT * FROM meccano_config';
         $funcName = $_POST['action'].'Config';
   }


   $funcName($DB->DB_Fetch(), $_POST['type']);
}


if(file_exists(ROOT . CACHE .'/phrases.system.inc'))
{
   $backups[] = 'system';
}
if(file_exists(ROOT . CACHE .'/phrases.users.inc'))
{
   $backups[] = 'users';
}
if(file_exists(ROOT . CACHE .'/config.inc'))
{
   $backups[] = 'config';
}

?>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <link rel="StyleSheet" type="text/css" href="/tpa/admin.css" />
      <style type="text/css">
         ul {
            list-style-type: none;
            width: 300px;
            text-align: left;
            margin-top: 50px;
         }
         ul li h3 {
            margin-bottom: 10px;
         }
      </style>
   </head>
   <body>
      <div align="center">
         <form action="/tools/lph.php" method="post">
            <input type="hidden" name="action" value="save" />
            <ul>
               <li><h3>Do backup for lang variables:</h3></li>
               <li><input type="checkbox" class="box" name="type" value="system" id="v_system" /> <label for="v_system"> - System vars</label></li>
               <li><input type="checkbox" class="box" name="type" value="users" id="v_users" /> <label for="v_users"> - Users vars</label></li>
               <li><input type="checkbox" class="box" name="type" value="config" id="v_config" /> <label for="v_config"> - Config vars</label></li>
               <li><input type="submit" class="btn" value="Save backup" /></li>
            </ul>
         </form>
         <?php if(!empty($backups)): ?>
         <form action="/tools/lph.php" method="post">
            <input type="hidden" name="action" value="restore" />
            <ul>
               <li><h3>Restore lang variables from backup:</h3></li>
               <?php for($i=0, $t=count($backups); $i<$t; $i++): ?>
               <li>
                  <input type="checkbox" class="box" name="type" value="<?=$backups[$i]; ?>" id="<?=$backups[$i]; ?>" />
                  <label for="<?=$backups[$i]; ?>"> -
                     <?php
                        switch($backups[$i])
                        {
                           case 'system':
                              echo 'System';
                           break;

                           case 'users':
                              echo 'Users';
                           break;

                           case 'config':
                              echo 'Config';
                        }
                     ?> vars</label>
               </li>
               <?php endfor; ?>
               <li><input type="submit" class="btn" value="Restore backup" /></li>
            </ul>
         </form>
         <?php endif; ?>
      </div>
   </body>
</html>
<?php


function saveVars($vars, $type, $save = TRUE)
{
   if(!is_array($vars)) return false;
   $lang = array();
   for($i=0, $t=count($vars); $i<$t; $i++)
   {
      if($vars[$i]['key'])
         $lang[$vars[$i]['lang']][$vars[$i]['name']][$vars[$i]['key']] = $vars[$i]['value'];
      else
         $lang[$vars[$i]['lang']][$vars[$i]['name']] = $vars[$i]['value'];
   }

   if($save)
      file_put_contents(ROOT . CACHE .'/phrases.'. $type .'.inc', serialize($lang));
   else
      return $lang;
}


function saveConfig($vars)
{
   if(!is_array($vars)) return false;
   $config = array();
   for($i=0, $t=count($vars); $i<$t; $i++)
   {
      $tmp = array();
      $tmp['value']       = $vars[$i]['value'];
      $tmp['type']        = $vars[$i]['type'];
      $tmp['description'] = $vars[$i]['description'];
      $tmp['system']      = $vars[$i]['system'];

      $config[$vars[$i]['name']] = $tmp;
   }

   file_put_contents(ROOT . CACHE .'/config.inc', serialize($config));
}


function restoreVars($vars, $type)
{
   if(!file_exists(ROOT . CACHE .'/phrases.'. $type .'.inc')) return FALSE;
   $lang = array();
   $backups = file_get_contents(ROOT . CACHE .'/phrases.'. $type .'.inc');
   $backups = unserialize($backups);
   $lang = saveVars($vars, $type, FALSE);

   if(!is_array($backups)) return FALSE;

   $new_vars = array();
   foreach($backups AS $lid=>$arr)
   {
      foreach ($arr AS $name=>$key)
      {

         if(is_array($key))
         {
            foreach($key AS $k=>$v)
            {
               if(!isset($lang[$lid][$name][$k]))
               {
                  $tmp = array();
                  $tmp['lang']  = $lid;
                  $tmp['name']  = $name;
                  $tmp['key']   = $k;
                  $tmp['value'] = $v;
                  $tmp['sys']   = $type == 'system' ? 1 : 0;

                  $new_vars[] = $tmp;
               }
            }
         } else
         {
            if(!isset($lang[$lid][$name]))
            {
               $tmp = array();
               $tmp['lang']  = $lid;
               $tmp['name']  = $name;
               $tmp['key']   = '';
               $tmp['value'] = $key;
               $tmp['sys']   = $type == 'system' ? 1 : 0;

               $new_vars[] = $tmp;
            }
         }
      }
   }

   if(!empty($new_vars))
   {
      global $DB;
      $id = $DB->DB_GetNextID('id', 'meccano_var');
      $sql = array();
      for($i=0, $t=count($new_vars); $i<$t; $i++)
      {
         $id++;
         $sql[] = '('. $id .', '. $new_vars[$i]['lang'] .', "'. $new_vars[$i]['name'] .'", "'. $new_vars[$i]['key'] .'", "'. $new_vars[$i]['value'] .'", "'. $new_vars[$i]['sys'] .'")';
      }

      echo 'Restored '. $t .' Language variables<br />';
      $DB->sql = 'INSERT INTO `meccano_var` (`id`, `lang`, `name`, `key`, `value`, `sys`) VALUES '. implode(',', $sql);
      $DB->DB_Query();
   }
}


function restoreConfig($vars)
{
   if(!file_exists(ROOT . CACHE .'/config.inc')) return FALSE;
   $config = array();
   $backups = file_get_contents(ROOT . CACHE .'/config.inc');
   $backups = unserialize($backups);

   if(!is_array($backups)) return FALSE;

   for($i=0, $t=count($vars); $i<$t; $i++)
   {
      if(isset($backups[$vars[$i]['name']])) unset($backups[$vars[$i]['name']]);
   }

   if(!empty($backups))
   {
      global $DB;
      $sql = array();
      foreach($backups AS $name=>$values)
      {
         $sql[] = '("'. $name. '", "'. mysql_real_escape_string($values['value']) .'", "'. $values['type'] .'", "'. mysql_real_escape_string($values['description']) .'", "'. $values['system'] .'")';
      }


      echo 'Restored '. count($backups) .' Config variables<br />';
      $DB->sql = 'INSERT INTO `meccano_config` (`name`, `value`, `type`, `description`, `system`) VALUES '. implode(',', $sql);
      $DB->DB_Query();
   }
}
